<template>
    <div class="px box" id="answerSheet">
        <el-row :gutter="10" v-if="err==null">
            <el-col :span="16">
                <el-card>
                    <div slot="header" class="clearfix">
                        <i class="el-icon-tickets"></i>
                        考试答题卷
                    </div>
                    <div>
                        <div v-if="$store.state.answerMode === 1">
                            <h2 style="text-align: center;"> {{examInfo.examName}}</h2>
                            <h2 style="text-align: center;"> 考试答题卷</h2>
                            <p style="font-size: 14px;color: darkgray;padding-left: 15px;">
                                <span>题数：{{testPaper.length}}</span>
                                &emsp;
                                <span>考试时长：{{(new Date(examInfo.examOverTime).getTime()-new
                                        Date(examInfo.examBeginTime).getTime())/60000+'分钟' }}</span>
                            </p>
                        </div>
                        <div style="transition: all 1s;">
                            <el-form
                                    v-for="(item,index) in testPaper"
                                    :key="index"
                                    :id="'timu'+(index+1)"
                                    v-show="showItem(index+1)"
                                    :inline="false"
                                    label-position="right"
                                    @submit.native.prevent
                                    label-width="10px">
                                <el-card class="box-card" style="margin-top: 15px">
                                    <div slot="header" class="clearfix">
                                        <h4>第{{index+1}}题：</h4>
                                    </div>

                                    <el-form-item :style="{width: '100%'}">
                                        {{item.question}}
                                    </el-form-item>

                                    <!--作答-->

                                    <!--单选题答案-->
                                    <el-form-item v-if="item.type===1" :style="{width: '100%'}">
                                        <el-radio-group @change="didItem(index+1)" v-model="answer[index].rightKey"
                                                        class="option-radio">
                                            <div class="option-item-radio">
                                                <el-radio :label="'a'">
                                                    A. {{item.questionOption.optionA}}
                                                </el-radio>
                                            </div>
                                            <div class="option-item-radio">
                                                <el-radio :label="'b'">
                                                    B. {{item.questionOption.optionB}}
                                                </el-radio>
                                            </div>
                                            <div class="option-item-radio">
                                                <el-radio :label="'c'">
                                                    C. {{item.questionOption.optionC}}
                                                </el-radio>
                                            </div>
                                            <div class="option-item-radio">
                                                <el-radio :label="'d'">
                                                    D. {{item.questionOption.optionD}}
                                                </el-radio>
                                            </div>
                                        </el-radio-group>
                                    </el-form-item>
                                    <!--多选题答案-->
                                    <el-form-item v-if="item.type===2" :style="{width: '100%'}"
                                    >
                                        <el-checkbox-group @change="(value)=>didCheckBoxItem(value,index+1)"
                                                           v-model="answer[index].checkList">
                                            <div class="option-item">
                                                <el-checkbox
                                                        :label="'a'">
                                                    A. {{item.questionOption.optionA}}
                                                </el-checkbox>
                                            </div>
                                            <div class="option-item">
                                                <el-checkbox
                                                        :label="'b'">
                                                    B. {{item.questionOption.optionB}}
                                                </el-checkbox>
                                            </div>
                                            <div class="option-item">
                                                <el-checkbox
                                                        :label="'c'">
                                                    C. {{item.questionOption.optionC}}
                                                </el-checkbox>
                                            </div>
                                            <div class="option-item">
                                                <el-checkbox
                                                        :label="'d'">
                                                    D. {{item.questionOption.optionD}}
                                                </el-checkbox>
                                            </div>


                                        </el-checkbox-group>
                                    </el-form-item>


                                    <!--主观题答案-->
                                    <el-form-item v-if="item.type===5"
                                                  :style="{width: '100%'}">
                                        <el-input
                                                @input="didInputItem($event,index+1)"
                                                v-model="answer[index].rightKey" type="textarea" placeholder="请输入"
                                                :autosize="{ minRows: 6, maxRows: 8}"
                                                maxlength="300"
                                                show-word-limit
                                                :style="{width: '100%'}"></el-input>
                                    </el-form-item>
                                    <!--填空题答案-->
                                    <el-form-item v-if="item.questionFillBlank!=null&&item.type===3"
                                                  :style="{width: '100%'}">
                                        <el-input
                                                @input="(value)=>didInputItem(value,index+1)"
                                                v-model="answer[index].rightKey"
                                                size="small"
                                                placeholder="请输入"
                                                clearable>
                                        </el-input>
                                    </el-form-item>
                                    <!--判断题答案-->
                                    <el-form-item v-if="item.questionJudgment!=null"
                                                  :style="{width: '100%'}">
                                        <el-radio-group
                                                @change="didItem(index+1)"
                                                v-model="answer[index].rightKey">
                                            <el-radio label="T">A. 对</el-radio>
                                            <el-radio label="F">B. 错</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <!--作答over-->
                                </el-card>
                            </el-form>
                            <div style="text-align: center;margin: 30px auto;"
                                 v-if="$store.state.answerMode === 2">
                                <el-button size="mini" type="primary"
                                           :disabled="1===current"
                                           @click="currentPrev">
                                    上一题
                                </el-button>
                                <span style="color: #00a1ff;">
                                    {{current}} / {{testPaper.length}}
                                </span>
                                <el-button size="mini" type="primary"
                                           :disabled="this.testPaper.length===current"
                                           @click="currentNext">
                                    下一题
                                </el-button>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8" style="position: relative;">
                <div id="tool-tip" :style="{'top':toolTipTop}">
                    <toolTip
                            :exam-info="examInfo"
                            :err="err"
                            :len="testPaper.length"
                            @submit="submit()"
                            @myInfo="myInfo()"
                            @changeCurrent="childChangeCurrent"
                    />
                </div>
            </el-col>
        </el-row>

        <div else>
            <h1 style="text-align: center;margin-top: 200px;">
                {{err}}
            </h1>
        </div>
    </div>

</template>

<script>
    import {answerSheetTestPaper, getExaminationById, submitAnswerSheet} from "../../../api/examination";
    import toolTip from "./toolTip";

    export default {
        name: "index",
        components: {toolTip},
        data() {
            return {
                id: null,
                examInfo: {},
                testPaper: [],//试卷
                answer: [],//答题卡
                toolTipTop: "0",
                err: null,
                current: 1,
            }
        },
        created() {
        },
        mounted() {
            this.init();
            this.getTestPaper();
        },
        beforeDestroy() {
            this.removeScrollListener();
            this.canCopy();
            //刷新的时候 持久化答题卡
        },
        methods: {
            handleScroll() {
                this.toolTipTop = Math.ceil(document.getElementById("answerSheet").scrollTop) + "px"
            },
            scrollListener() {
                window.addEventListener('scroll', this.handleScroll, true)
            },
            removeScrollListener() {
                window.removeEventListener('scroll', this.handleScroll, true)

            },
            init() {
                if (this.$route.params.id) {
                    this.$store.commit("setAnswerSheetId", this.$route.params.id)
                }
                this.id = this.$store.state.answerSheetId;
            },
            async getExamInfo() {
                let resp = await getExaminationById(this.id)
                this.examInfo = resp.data
            },
            async getTestPaper() {
                let resp = await answerSheetTestPaper(this.id)
                if (resp.code !== 200) {
                    this.$message.warning(resp.message)
                    this.$store.commit("setAnswerSheetId", null)
                    this.err = resp.message
                    return false;
                }
                this.testPaper = resp.data

                for (let i = 0; i < this.testPaper.length; i++) {
                    this.answer.push({
                        id: this.testPaper[i].id,
                        type: this.testPaper[i].type,
                        rightKey: null,
                        checkList: []
                    })
                }

                this.getExamInfo();
                this.noCopy()
                this.scrollListener()
                document.title = "在线考试";
                return true;
            },
            async submit() {
                //处理答案发送给后端
                this.answer.forEach(item => {
                    if (item.type === 2) {
                        try {
                            item.rightKey = item.checkList.sort().toString().replaceAll(",", "")
                        } catch (e) {

                        }
                    }
                })
                let resp = await submitAnswerSheet(this.id, this.answer)
                if (resp.code !== 200) {
                    this.$message.warning(resp.message)
                } else {
                    document.title = "在线考试系统";
                    this.exit()
                }
                this.canCopy();
                this.$store.commit("setAnswerSheetId", null)
            },
            myInfo() {
                console.log("myInfo")
            },
            exit() {
                this.$confirm("已交卷，请退出考试界面", '提示', {type: "success"}).then(() => {

                }).catch(err => {

                }).finally(() => {
                    this.$router.replace("/ei")
                })
            },
            noCopy() {
                this.$nextTick(() => {
                    document.oncontextmenu = new Function("event.returnValue=false");
                    document.onselectstart = new Function("event.returnValue=false");
                });
            },
            canCopy() {
                this.$nextTick(() => {
                    document.oncontextmenu = null
                    document.onselectstart = null
                });
            },
            showItem(i) {
                if (this.$store.state.answerMode === 1) {
                    return true;
                }
                if (this.$store.state.answerMode === 2) {
                    if (this.current === i)
                        return true;
                }
            },
            currentPrev() {
                this.current = this.current === 1 ? 1 : this.current - 1
            },
            currentNext() {
                this.current = this.current === this.testPaper.length ? this.testPaper.length : this.current + 1

            },
            childChangeCurrent(obj) {
                this.current = obj.id;
            },
            //做了一道题
            didItem(i) {
                this.setAnsweredIds(i)
            },
            //做了一道题多选
            didCheckBoxItem(arr, i) {
                if (arr.length > 0) {
                    this.setAnsweredIds(i)
                } else {
                    this.setAnsweredIds(i, false)
                }
            },
            //做了一道题填空题
            didInputItem(value, i) {
                console.log(value)
                if (value.length > 0) {
                    this.setAnsweredIds(i)
                } else {
                    this.setAnsweredIds(i, false)
                }
            },
            setAnsweredIds(i, addFlag = true) {
                let arr = JSON.parse(this.$store.state.answeredIds)
                if (arr == null) {
                    arr = []
                }
                if (addFlag) {
                    if (!arr.includes(i)) {
                        arr.push(i)
                    }
                } else {
                    arr.splice(arr.indexOf(i), 1);
                }
                this.$store.commit("setAnsweredIds", JSON.stringify(arr));
            },

        },
        watch: {
            current(newVal) {
                this.showItem(newVal)
            }
        }
    }
</script>

<style scoped lang="scss">
    .box {
        height: 100vh;
        overflow: auto;
    }

    h4 {
        margin: 0;
    }

    .el-form-item {
        margin: 20px 10px;
    }

    #tool-tip {
        width: 100%;
        transition: 0.3s;
        position: absolute;
        left: 0;
        right: 0
    }

    .option-radio {
        padding-top: 15px;

        .option-item-radio {
            margin: 0 5px 15px;

        }
    }

    .option-item {
        margin: 0 5px 0;
    }
</style>